package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 张一恒
 * @version 1.0
 * @description: 自媒体获取用户信息存入本地线程
 * @date 2023/1/11 15:28
 */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    /**
     * 调用服务接口前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取头中userid
        String userId = request.getHeader("userId");
        if (!StringUtils.isEmpty(userId)){
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.parseInt(userId));
            WmThreadLocal.setUser(wmUser);
            log.debug("调用自媒体服务接口前执行用户id获取成功：{}",userId);
        }else {
            log.debug("调用自媒体服务接口前执行用户id获取失败：{}",userId);
        }


        return true;
    }

    /**
     * @description 调用服务接口后执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @return void
     * @author 31115
     * @date 2023/1/11 15:32
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //释放
        WmThreadLocal.clear();
    }
}
